/*
 * 检测是IOS还是安卓
 * @return {{isIos:Function, isAndroid:Function}}
 */
function getBrowserVersion() {
    const ua = navigator.userAgent || navigator.vendor || window.opera
    const uaInfo = {
        ios: /\(i[^;]+;( U;)? CPU.+Mac OS X/i.test(ua),
        android: /Android/i.test(ua) || /Linux/i.test(ua)
    }
    return {
        isIos() {
            return uaInfo.ios
        },
        isAndroid() {
            return uaInfo.android
        }
    }
}

/**
 * 生成指定长度的随机字符串序列
 * @param {number?} len
 * @returns {string}
 */
function randomString(len = 32) {
    const chars = 'GQM5s7KdZhr8zFV3X4CHfU6kIq2cgTBDnoJamSyNOeYW9Rt01pLblvwiuPExjA'
    const maxPos = chars.length
    let pwd = ''
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
}

/* localStorage存储封装 */
const localStorage = {
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    get(key) {
        return JSON.parse(localStorage.getItem(key));
    },
    remove() {
        localStorage.removeItem(key)
    }
}

/* sessionStorage存储封装 */
const sessionStorage = {
    set(key, value) {
        sessionStorage.setItem(key, JSON.stringify(value));
    },
    get(key) {
        return JSON.parse(sessionStorage.getItem(key));
    },
    remove() {
        sessionStorage.removeItem(key)
    }
}

/* js浮点数相加解决精度问题 */
/* example: (0.1).add(0.2) */
function floatAdd(num) {
    //取两个数值中小数位最大的
    let n1 = this.toString().split('.')[1].length
    let n2 = num.toString().split('.')[1].length

    //得到10的N次幂
    let m = Math.pow(10, Math.max(n1, n2))

    return (this * m + num * m) / m
}

/* 防抖函数 立即执行/稍后执行 */
function debounce(fcn, wait, immediate) {
    let timer;
    return function() {
        if (immediate) {
            let tmp = !timer;
            if (tmp) {
                fcn.apply(this, arguments)
            }
            timer = setTimeout(() => {
                timer = null;
            }, wait)
        } else {
            timer = setTimeout(() => {
                fcn.apply(this, arguments);
            }, wait)
        }
    }
}

/* 节流函数 立即执行/稍后执行 */
function throttle(fcn, wait, immediate) {
    let timer;
    return function() {
        let tmp = true;
        if (immediate) {
            fcn.apply(this, arguments);
            tmp = false;
            timer = setTimeout(() => {
                tmp = true;
            }, wait)
        } else {
            tmp = false;
            timer = setTimeout(() => {
                fcn.apply(this, arguments);
                tmp = true
            }, wait)
        }
    }
}

export {
    getBrowserVersion,
    randomString,
    floatAdd,
    debounce,
    throttle,
    localStorage,
    sessionStorage,
}